package com.google.code.mochaccino.framework.jmx;
/*
 * Copyright 2012 Claude Houle claude.houle@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * JMX Connection IMPL
 *
 * @author choule
 */
public class JmxConnectionImpl implements  JmxConnection {

	private static final Logger logger = LoggerFactory.getLogger( JmxConnectionImpl.class );

	private MBeanServerConnection connection;
	private JMXConnector          connector;
	private String                host;
	private int                   port;
	private JMXServiceURL         serviceURL;
	private String                url;

	/* (non-Javadoc)
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
	 */
	@PostConstruct
	public void init() throws Exception {
		try {
			url = "service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi";
			serviceURL = new JMXServiceURL( url );
			connector = JMXConnectorFactory.connect( serviceURL );
			connection = connector.getMBeanServerConnection();
		} catch ( Exception e ) {
			logger.error( e.getMessage(), e );
		}
	}

	@PreDestroy
	public void destroy() throws Exception {
		connector.close();
	}

	@Override
	public MBeanServerConnection getConnection() {
		return connection;
	}

	/**
	 * @return the host
	 */
	public String getHost() {
		return host;
	}

	/**
	 * @param host the host to set
	 */
	public void setHost( String host ) {
		this.host = host;
	}

	/**
	 * @return the port
	 */
	public int getPort() {
		return port;
	}

	public void setPort( int port ) {
		this.port = port;
	}

	/**
	 * @return the url
	 */
	public String getUrl() {
		return url;
	}

	/**
	 * @param url the url to set
	 */
	public void setUrl( String url ) {
		this.url = url;
	}
}
